<script>
import props from './props'
import { setTimeout } from 'timers';
export default {
  name: 'eco-navigate',
  props,
  computed: {
    list () {
      return [
        this.action + '/eco-global-style.css',
        this.action + '/eco-navigation.css',
        this.action + '/eco-navigation-config.js',
        this.action + '/eco-global-business.js',
        this.action + '/eco-navigation.js'
      ]
    }
  },
  methods: {
    compareUrl (obj, key, src) {
      let vm = this
      let rdata = false
      obj.forEach(itm => {
        if (vm.list.includes(itm[key])) {
          rdata = true
          return rdata
        } else if (itm[key].indexOf(src) > -1) {
          obj.parentNode.removeChild(itm)
        }
      })

      return rdata
    },
    appendJQCDN (src, callback) {
      let head = document.head || document.getElementsByTagName('head')[0]
      if (src.indexOf('.css') > -1) { // css
        let style = document.createElement('link')
        style.setAttribute('rel', 'stylesheet')
        style.setAttribute('href', src)
        head.appendChild(style)
      } else if (src.indexOf('.js') > -1) {
        let script = document.createElement('script')
        script.type = 'text/javascript'
        script.setAttribute('src', src)
        if (typeof (callback) !== 'undefined') {
          if (script.readyState) {
            script.onreadystatechange = function () {
              if (script.readyState === 'loaded' || script.readyState === 'complete') {
                script.onreadystatechange = null
                callback()
              }
            }
          } else {
            script.onload = function () {
              callback()
            }
          }
        }
        head.appendChild(script)
      }
    },
    loadScript (url, callback) {
      let vm = this

      let headcss = document.querySelectorAll('head link')
      let headjs = document.querySelectorAll('head script')

      vm.list.forEach((itm, idx) => {
        let add = false
        let compare = itm.slice(itm.lastIndexOf('/'))
        if (itm.indexOf('.css') === -1) {
          add = vm.compareUrl(headjs, 'src', compare)
        } else {
          add = vm.compareUrl(headcss, 'href', compare)
        }

        if (!add && idx === vm.list.length - 1) {
          vm.appendJQCDN(itm, function () {
            vm.loadHandle()
          })
        } else if (!add) {
          vm.appendJQCDN(itm)
        }
      })
    },
    loadHandle () {
      let i = this.data && this.data.length > 0 ? this.data[0] : {}
      window.removeEventListener('load', onloadHander)
      new EcoNavigation(i)
    }
  },

  mounted () {
    this.loadScript()
  },

  watch: {
    list () {
      this.loadScript()
    }
  }
}
</script>
